<?php


namespace app\service\user;


use app\model\coach\UserCoachModel;
use app\model\partner\UserPartnerModel;
use app\model\user\UserModel;
use app\service\BaseService;
use app\service\config\ConfigService;

class UserService extends BaseService
{

    public function __construct()
    {
        $this->model = new UserModel();
    }

    /**
     * 分佣
     * @param $userId
     * @param $orderAmount
     * @param $orderSn
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function award($userId, $orderAmount, $orderSn)
    {
        $ratio = ConfigService::getConfigValue('share_ratio', 0);
        if ($ratio <= 0) {
            return true;
        }
        $award = bcmul($orderAmount, $ratio / 100, 2);

        $userInfo = UserModel::find($userId);
        $shareType = $userInfo['share_type'];
        if($shareType == 0){
            $pid = $userInfo['pid'];
            $pInfo = UserModel::find($pid);
            if (!$pInfo) {
                return true;
            }
            $detailMoneyService = new UserMoneyDetailService();
            $type = UserMoneyDetailService::INVITE_USER_BUY;
            $title = sprintf($type, $userInfo['username']);
            $detailMoneyService->createLog($title, $pid, $type, $award, $userId, $orderSn);
        }elseif ($shareType == 1){
            $pid = $userInfo['coach_id'];
            $pInfo = UserCoachModel::find($pid);
            if (!$pInfo) {
                return true;
            }
            $detailMoneyService = new CoachMoneyDetailService();
            $type = CoachMoneyDetailService::INVITE_USER_BUY;
            $title = sprintf($type, $userInfo['username']);
            $detailMoneyService->createLog($title, $pid, $type, $award, $userId, $orderSn);
        }else{
            $pid = $userInfo['partner_id'];
            $pInfo = UserPartnerModel::find($pid);
            if (!$pInfo) {
                return true;
            }
            $detailMoneyService = new PartnerMoneyRecordService();
            $type = PartnerMoneyRecordService::INVITE_USER_BUY;
            $title = sprintf($type, $userInfo['username']);
            $detailMoneyService->createLog($title, $pid, $type, $award, $userId, $orderSn);
        }
        return true;
    }
}